Intent是應用程式元件(Activity、Service、BroadcastReceiver、ContentProvider)的溝通橋樑,用來實現多個畫面轉換
startActivity(Intent(this, SecActivity::class.java))
用上述程式碼,可讓SecActivity覆蓋於this上
傳送單筆
var intent = Intent(this, SecActivity::class.java)
intent.putExtra("key","value")
startActivity(intent)
傳送多筆
var bundle = Bundle()
bundle.putInt("key1",123)
bundle.putString("key2","ABC")
var intent = Intent(this, SecActivity::class.java)
intent.putExtras(bundle)
startActivity(intent)
接收數據
intent?.extras>.let{ //判斷intent不為空且有夾帶資料
val value1 = it.getInt("key1")
val value2 = it.getInt("key2")
}
//取回資料
override fun onActivityResult(requestCode: Int,resultCode: Int, data:Intent?) {
super.onActivityResult(requestCode,resultCode,data)
data?.extras?.let{
if(requestCode ==1 && requestCode == Activity.RESULT_OK){
...//取得返回資料
}
}
}
//建立資料
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var bundle = Bundle()
bundle.putInt("key1",123)
bundle.putString("key2","ABC")
var intent = Intent(this, SecActivity::class.java)
intent.putExtras(bundle)
startActivityForResult(intent,1)
}
setResult(Activity.RESULT_OK,intent) //設定要返回的資料
finish() //結束自身週期,